/** @odoo-module **/
import {Toast} from './components/Toast.js';
import {Record} from './components/Record.js';
import {
    arrayRemoveRepeat,
    keepTwoDecimal,
    toObj,
    formatId,
    formatPrice,
    formatDate,
    fullScreen,
    fullExit,
    onFullscreenChange,
    add_site_stock_record_id,
    add_stock_out_record_detail_id
} from "./ag_grid/tool.js";

const {
    markup,
    Component,
    onWillStart,
    useEnv,
    useSubEnv,
    useChildSubEnv,
    useRef,
    useState,
    mount,
    xml,
    whenReady,
    onMounted,
    onError,
    EventBus,
    loadFile,
    onWillUpdateProps,
    useEffect,
    onWillUnmount,
    useComponent
} = owl;



class Root extends Component {

    setup() {

        console.log(this.props);

        this.bus = new EventBus();

        this.tmp_user_vals = {};

        // this.timer = setInterval(async () => {
        //
        //     this.update_user_settings_in_batch();
        //
        // }, 5000)

        onWillUnmount(() => {
            // clearInterval(this.timer);
        })
        useSubEnv({
            bus: this.bus
        })

        useChildSubEnv({// 只会在组件的子组件中挂载公共数据及方法
            closeToast: () => {
                this.state.toastOpen = false;
                this.state.toastData = {};
            },
            openToast: (d) => {
                this.state.toastData = d;
                this.state.toastOpen = true;
            },
            getIndex: () => {
                return JSON.parse(JSON.stringify(this.index));
            },
            getGlobal: () => {
                return JSON.parse(JSON.stringify(this.global));
            },
            searchUnit: (material_id) => {
                return this.searchUnit(material_id);
            },
            get_year_month_day:()=>{
                return this.year_month_day
            },
            setHaveChange:(flag)=>{
                this.state.haveChange = flag;
            },
            stockOutRecord:(dinner_type_id)=>{
                return this.stockOut(dinner_type_id);
            },
            saveRecord:()=>{
                return this.save();
            },
            LoadSecDataFlag:()=>{
                return this.state.LoadSecDataFlag;
            },
            LoadSecData:()=>{
                return this.LoadSecDataFlag();
            },
            getMainUnitBomUnitRatio:(material_id,unit_id)=>{
                return this.getMainUnitBomUnitRatio(material_id,unit_id)
            }
        });

        this.index = {};//页面使用的数据
        this.global = {};


        this.year_month_day = this.props.year_month_day;
        this.state = useState({
            haveChange:false,//是否发生修改
            isMenuMode: true,
            toastOpen: false,
            toastData: {},//提示消息
            isUpdateProps:false, //生命周期标志
            LoadSecDataFlag:false
        });

        onWillStart(async () => await this.LoadData(this.props.year_month_day));
        onWillUpdateProps(async next_props => {
            this.state.isUpdateProps = true;
            await this.LoadData(next_props.year_month_day)
        });
        onMounted(()=>{
            onFullscreenChange((e)=>{return this.onFullscreenChange(e)})
        });

        this.handle_select_year_month_day = _.debounce(this.select_year_month_day,300);
        this.handleSave = _.debounce(this.save,300);
        this.handleToggleMenuMode = _.debounce(this.toggleMenuMode,300);
        this.handle_print = _.debounce(this.print,300);
    }
    async save(e) {
        if(!this.state.haveChange){
            return;
        }
        let obj = {
            create_vals_list:[],
            write_vals_list:[],
            unlink_ids:[]
        };
        this.bus.trigger('save_record',obj);
        // if(obj.create_vals_list.length == 0 && obj.write_vals_list.length == 0 && obj.unlink_ids.length == 0){
        //     return;
        // }
        console.log('保存的数据',obj);
        let {create_vals_list, write_vals_list, unlink_ids} = obj;
        if(create_vals_list.length > 4 * 5 * 10){
            this.state.toastData = {
                msg:'当前保存的数据较多，请耐心等待...'
            };
            this.state.toastOpen = true;
        }

        let res;

        if (this.props.SiteStockRecordUpdateData) {
            res = await this.props.SiteStockRecordUpdateData(this.props.year_month_day, create_vals_list, write_vals_list, unlink_ids);

        } else {
            res = await this.requestSave(obj);
        }
        let { new_ids } = res;
        let site_stock_record = this.index.site_stock_record;
        if(unlink_ids.length>0){
            // 更新库存
            let stock_out_diff_obj= {};
            let del_site_stock_record = site_stock_record.filter(v=>obj.unlink_ids.includes(v.id));
            del_site_stock_record.forEach(v=>{
                let { material_id } = v;
                !stock_out_diff_obj[material_id] && (stock_out_diff_obj[material_id] = 0);
                if(v.stock_out_qty){
                    stock_out_diff_obj[material_id] -= v.stock_out_qty;
                }
            })
            // 更新库存
            for(let material_id in stock_out_diff_obj){
                this.global.material_stock_qty[material_id].stock_qty -= stock_out_diff_obj[material_id]
            }
            site_stock_record = site_stock_record.filter(v=>!obj.unlink_ids.includes(v.id));
        }

        let write_ids = obj.write_vals_list.map(v=>v.id);
        site_stock_record = site_stock_record.filter(v=>!write_ids.includes(v.id));
        site_stock_record = site_stock_record.concat(obj.write_vals_list);
        obj.create_vals_list.forEach((v,i)=>{
            v.id = new_ids[i]
        })
        site_stock_record = site_stock_record.concat(obj.create_vals_list);
        this.index.site_stock_record = site_stock_record;
        if(typeof e == 'number' && e === 0){
            // 不刷新表格
        }else{
            this.bus.trigger('save_record_ok',res);
        }
    }
    async stockOut(dinner_type_id){
        dinner_type_id = formatId(dinner_type_id);

        await this.save(0);
        console.log('出库',dinner_type_id);

        let res;
        if (this.props.SiteStockRecordUpdateStockOutData) {
            res = await this.props.SiteStockRecordUpdateStockOutData(this.props.year_month_day, [dinner_type_id]);
        } else {
            res = await this.requestStockOut(dinner_type_id);
        }
        let {
            // stock_out_record_detail,
            update_vals_list
        } = res;
        // let old_stock_out_record_detail = this.index.stock_out_record_detail;
        let site_stock_record = this.index.site_stock_record;
        // let replace_stock_out_record_detail_ids = site_stock_record.filter(v=>v.dinner_type_id === dinner_type_id).map(v=>v.stock_out_record_detail_id);
        // old_stock_out_record_detail = old_stock_out_record_detail.filter(v=>!replace_stock_out_record_detail_ids.includes(v.id));
        // this.index.stock_out_record_detail = old_stock_out_record_detail.concat(stock_out_record_detail);
        let update_vals_obj = toObj(update_vals_list,'id');
        let stock_out_diff_obj= {};
        site_stock_record.forEach(v=>{
            if(update_vals_obj[v.id]){
                let { material_id } = v;
                v.stock_out_record_detail_id = update_vals_obj[v.id].stock_out_record_detail_id;
                !stock_out_diff_obj[material_id] && (stock_out_diff_obj[material_id] = 0);
                stock_out_diff_obj[material_id] += (v.unit_qty - (v.stock_out_qty||0));
                v.stock_out_qty = v.unit_qty;
            }
        })
        this.index.site_stock_record = site_stock_record;
        // 更新库存
        for(let material_id in stock_out_diff_obj){
            this.global.material_stock_qty[material_id].stock_qty -= stock_out_diff_obj[material_id]
        }
        // console.log(this.index.stock_out_record_detail);
        this.bus.trigger('stock_out_ok');
    }
    async print(){
        await this.save();
        console.log('打印');
    }
    onFullscreenChange(e){
        // console.log(e);
        let isMenuMode = false;
        if (document.fullscreenElement) {
            console.log('进入全屏')
        } else {
            console.log('退出全屏')
            isMenuMode = true;
        }
        this.state.isMenuMode = isMenuMode;
        if (this.props.toggleMenuMode) {
            this.props.toggleMenuMode(this.state.isMenuMode);
        }
    }
    toggleMenuMode() {
        if(this.state.isMenuMode){
            fullScreen()
        }else{
            fullExit()
        }
    }

    get year_month_day_list() {
        let today = new Date();
        let nowTime = today.getTime(); //当前的时间戳
        let oneDayTime = 24 * 60 * 60 * 1000; //一天的总ms
        let days = [];
        for (let i = -6; i < 8; i++) {
            let time = oneDayTime * i + nowTime;
            let date = new Date(time);
            days.push(formatDate(date, 'yyyy-mm-dd'))
        }
        return days;
    }

    // 切换日期
    async select_year_month_day(e) {
        let key = e.target.dataset.key;
        if (key == this.year_month_day) {
            return false
        }
        if (!this.state.haveChange) {
            //页面未产生修改
            this.props.PlanDayUpdateYearMonthDay(key);
            return false;
        }
        console.log('数据是否...');
        this.state.toastData = {
            msg: '确定保存当前"客户端领用"数据？',
            isCancel: true,
            onConfirm: async () => {
                await this.save(0);
                this.props.PlanDayUpdateYearMonthDay(key);
            },
            onCancel: async () => {

            }
        };
        this.state.toastOpen = true;
    }

    async LoadTestSecData(){
        let material_item = await fetch('./json/sec_data/material_item.json')
            .then((response) => response.json());
        let material_unit_ratio = await fetch('./json/sec_data/material_unit_ratio.json')
            .then((response) => response.json());
        return {
            material_item,
            material_unit_ratio
        }
    }

    async LoadTestData(year_month_day) {
        console.log('加载的数据: ', year_month_day);

        let cus_loc = await fetch('./json/cus_loc.json')
            .then((response) => response.json());
        let dinner_type_category = await fetch('./json/dinner_type_category.json')
            .then((response) => response.json());
        let material_item = await fetch('./json/material_item.json')
            .then((response) => response.json());
        let material_purchase_unit_category = await fetch('./json/material_purchase_unit_category.json')
            .then((response) => response.json());
        let material_top_category = await fetch('./json/material_top_category.json')
            .then((response) => response.json());
        let material_unit_ratio = await fetch('./json/material_unit_ratio.json')
            .then((response) => response.json());
        let org_config = await fetch('./json/org_config.json')
            .then((response) => response.json());
        let site_stock_record = await fetch('./json/site_stock_record.json')
            .then((response) => response.json());
        // let stock_out_record_detail = await fetch('./json/stock_out_record_detail.json')
        //     .then((response) => response.json());
        let user_config = await fetch('./json/user_config.json')
            .then((response) => response.json());

        return {
            cus_loc,
            dinner_type_category,
            material_item,
            material_purchase_unit_category,
            material_top_category,
            material_unit_ratio,
            org_config,
            site_stock_record,
            // stock_out_record_detail,
            user_config,
        }
    }
    async LoadData(year_month_day) {
        console.log(`加载数据 ${year_month_day}数据 `); // 开辟加载父类数据结构逻辑!!!
        let load_func = this.props.SiteStockLoadData ? this.props.SiteStockLoadData.bind(this) : this.LoadTestData.bind(this);

        let data = await load_func(year_month_day);


        let {
            cus_loc,
            dinner_type_category,
            material_item,
            material_purchase_unit_category,
            material_top_category,
            material_unit_ratio,
            org_config,
            site_stock_record,
            // stock_out_record_detail,
            user_config,
        } = data;
        // site_stock_record = [];
        cus_loc.sort((a, b) => {
            return a.cus_plan_no - b.cus_plan_no
        });
        cus_loc = cus_loc.filter(v=>{
            if(v.is_in_menu){
                return true
            }else{
                return false
            }
        });
        dinner_type_category.sort((a, b) => {
            return a.dt_no - b.dt_no
        });
        let site_material_item = material_item.filter(v=>v.is_site_use === 'True');
        let material_stock_qty = material_item.map(v=>{
            return {
                id: v.id,
                stock_qty: v.stock_qty
            }
        })
        this.index = {
            cus_loc,
            dinner_type_category,
            material_item,
            material_purchase_unit_category,
            material_top_category,
            material_unit_ratio,
            org_config,
            site_stock_record,
            // stock_out_record_detail,
            user_config,
            site_material_item
        };
        this.global = {
            cus_loc:toObj(cus_loc, 'cus_loc_id'),
            dinner_type_category:toObj(dinner_type_category, 'id'),
            material_item:toObj(material_item, 'id'),
            material_purchase_unit_category:toObj(material_purchase_unit_category,'id'),
            material_top_category:toObj(material_top_category,'id'),
            material_stock_qty:toObj(material_stock_qty,'id')
        };


        this.year_month_day = year_month_day;
        this.state.LoadSecDataFlag = false;
    }
    async LoadSecDataFlag(){
        console.log(`二次加载数据`);
        let load_func = this.props.SiteStockRecordLoadSecData ? this.props.SiteStockRecordLoadSecData.bind(this) : this.LoadTestSecData.bind(this);
        let data = await load_func();
        let {
            material_item,
            material_unit_ratio,
        } = data;
        let material_stock_qty = material_item.map(v=>{
            return {
                id: v.id,
                stock_qty: v.stock_qty
            }
        })
        this.index.material_item = material_item;
        this.index.material_unit_ratio = material_unit_ratio;
        this.global.material_item = toObj(material_item, 'id');
        this.global.material_stock_qty = toObj(material_stock_qty, 'id');

        this.state.LoadSecDataFlag = true;
    }
    getMainUnitBomUnitRatio(material_id,unit_id){
        let main_unit_id = this.global.material_item[material_id].main_unit_id;
        // const main_item = this.index.material_unit_ratio.find(v => v.material_id == material_id && v.unit_id == main_unit_id);
        const unit_item = this.index.material_unit_ratio.find(v => v.material_id == material_id && v.unit_id == unit_id);
        let ratio = 0;
        try {
            // ratio = unit_item.jin_ratio/main_item.jin_ratio;
            ratio = unit_item.unit_ratio;
        }catch (e) {}
        return ratio
    }
    requestSave(obj){
        let new_ids = obj.create_vals_list.map(v=>v.id);
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve({new_ids});
            }, 1000);
        });
    }
    requestStockOut(dinner_type_id){
        // let stock_out_record_detail = [];
        let update_vals_list = [];

        let site_stock_record = this.index.site_stock_record.filter(v=>v.dinner_type_id === dinner_type_id);
        let obj = {};
        site_stock_record.forEach(v=>{
            !obj[v.material_id] && (obj[v.material_id] = {
                id:add_stock_out_record_detail_id(),
                main_unit_qty:0,
                main_unit_id:v.unit_id
            });
            obj[v.material_id].main_unit_qty += v.unit_qty
            v.stock_out_record_detail_id = obj[v.material_id].id
        })
        // for(let material_id in obj){
        //     stock_out_record_detail.push(obj[material_id]);
        // }
        update_vals_list = site_stock_record.map(v=>{
            return {
                id:v.id,
                stock_out_record_detail_id:v.stock_out_record_detail_id
            }
        });
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve({
                    // stock_out_record_detail,
                    update_vals_list
                });
            }, 1000);
        });
    }
}


Root.template = 'Site_stock_record_Root';

Root.props = {
    year_month_day: {type: String},
    toggleMenuMode: {type: Function, optional: true},
    PlanDayUpdateYearMonthDay: {type: Function},
    SiteStockLoadData: {type: Function, optional: true},
    SiteStockRecordUpdateData: {type: Function, optional: true},
    SiteStockRecordUpdateStockOutData: {type: Function, optional: true},
    SiteStockRecordLoadSecData: {type: Function, optional: true},
}

Root.components = {
    Toast,
    Record
    // CreatMaterialModal,
    // UnitRatioModal,
}

export {
    Root
}
